import React, { useState, useEffect, useRef } from 'react';
import { Form, Button, Checkbox, Input, Skeleton, App } from 'antd';
import { MobileOutlined, MessageOutlined, CommentOutlined } from '@ant-design/icons';
import loadable from '@loadable/component';
import { useHistory } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import pMinDelay from 'p-min-delay';

import useDevice, { DEVICES } from '@/hooks/useDevice';
import { AGREEMENT } from '@/config/url';
import { isRegMobile } from '@/utils';
import { login } from '@/service/base';
import { setStore } from '@/reducers/common';

import styles from './index.module.scss';

const GetCaptcha = loadable(() => pMinDelay(import('@/pages/components/GetCaptcha'), 0), { fallback: <Skeleton.Button style={{height:18}} active/> });

export default (props) => {
    const initState = () => ({
        submitting: false,
    });
    const [state, setState] = useState(initState);
    const { message } = App.useApp();
    const {onOk, onCancel} = props;
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    const isDesktop = DEVICES.DESKTOP === useDevice();

    // 工具函数
    const loading = (flag=true) => setState(o => ({...o, submitting: flag}));

    // 展示绑定弹框
    const showBind = () => {
        dispatch(setStore({
            loginVisible: false,
            bindVisible: true,
            bindType: 'qrcode',
        })); // sms, qrcode
    };

    // 提交表单
    const onFinish = values => {
        message.destroy();
        loading();

        const formData = new FormData();
        // 邀请码
        const inviter_code = localStorage.getItem('_invitation') || '';
        if(inviter_code) formData.append('inviterCode', inviter_code);

        formData.append('msg', values.msg);
        formData.append('phone', values.phone);

        login(formData).then(res => {
            if(OK_CODE !== res?.code) {
                loading(false);
                return message.warning(res?.message);
            }

            const {token, user: userInfo, expire} = res || {};

            // 设置token等信息后再跳转
            localStorage.setItem('accessToken', token);
            localStorage.removeItem('inviter_code');
            dispatch(setStore({userInfo}));

            // 绑定微信
            const accountOpenId = userInfo?.accountOpenId || '';
            if(!accountOpenId) return showBind();

            onOk(userInfo);
        }).catch(e => {
            loading(false);
            message.error(e?.message);
        });
    };

    return (
        <Form
            form={form}
            onFinish={onFinish}
            size="large"
            className={styles['sms-form']}
        >
            <Form.Item
                name="phone"
                rules={[
                    { required: true, message: '请输入手机号' },
                    { validator: (_, value) => {
                        if(value && !isRegMobile(value)) return Promise.reject(`请输入正确的手机号`);
                        return Promise.resolve();
                    }},
                ]}
            >
                <Input
                    type="tel"
                    prefix={<MobileOutlined />}
                    placeholder="手机号"
                />
            </Form.Item>
            <Form.Item
                noStyle
                shouldUpdate={(p,c) => p.phone !== c.phone}
            >
                {
                    ({getFieldValue}) => {
                        const phone = getFieldValue('phone');

                        return (
                            <Form.Item
                                name="msg"
                                rules={[
                                    { required: true, message: '请输入验证码' }
                                ]}
                            >
                                <Input
                                    prefix={<MessageOutlined />}
                                    suffix={
                                        <div className='captcha'>
                                            <GetCaptcha phone={phone} type="register"/>
                                        </div>
                                    }
                                    placeholder="验证码"
                                    type={isDesktop ? 'text' : 'number'}
                                />
                            </Form.Item>
                        );
                    }
                }
            </Form.Item>
            <Form.Item
                name="agreement"
                valuePropName="checked"
                rules={[
                    {
                        validator: (_, value) => {
                            if(value) return Promise.resolve();
                            return Promise.reject(new Error('请同意隐私政策'));
                        },
                    },
                ]}
                initialValue={true}
            >
                <Checkbox >阅读并同意 <a target="_blank" href={AGREEMENT}>隐私政策</a></Checkbox>
            </Form.Item>

            <Button
                loading={state.submitting}
                type="primary"
                htmlType="submit"
                block
            >
                登录&nbsp;/&nbsp;注册
            </Button>
        </Form>
    );
};